package com.xingshang.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xingshang.model.dto.GoodsDto;
import com.xingshang.model.po.Admin;
import com.xingshang.model.po.Category;
import com.xingshang.model.po.Goods;
import com.xingshang.model.po.User;
import com.xingshang.service.AdminService;
import com.xingshang.service.CategoryService;
import com.xingshang.service.GoodsService;
import com.xingshang.service.UserService;
import com.xingshang.util.RedisService;
import com.xingshang.service.impl.UserServiceImpl;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor


public class AdminController {
    private final RedisService redisService;



    private final CategoryService categoryService;
    private final GoodsService goodsService;
    private final UserServiceImpl userServiceImpl;
    private final AdminService adminService;

    @Value("${page.size}")
    private int PAGE_SIZE;

    @GetMapping("")
    public String admin(Model model, HttpSession session) {
        System.out.println("管理员页面");
        return "admin";
    }

    @GetMapping("/goods/add")
    public String goodsAdd(Model model, HttpSession session) {
        System.out.println("添加商品页面");
        List<Category> list = categoryService.list();
        model.addAttribute("categories", list);
        return "goods_add";
    }
    @GetMapping("/category/add")
    public String addCategory(Model model) {
        return "category_add";
    }
    @PostMapping("/manager/updateAccount")
    @ResponseBody
    public Map<String, Object> updateAdminAccount(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        String account = params.get("account");
        Integer id = Integer.valueOf(params.get("id"));

        if (StringUtils.isBlank(account)) {
            result.put("success", false);
            result.put("message", "用户名不能为空");
            return result;
        }

        // 检查用户名是否存在（排除自己）
        Admin existAdmin = adminService.findByAccountAndNotId(account, id);
        if (existAdmin != null) {
            result.put("success", false);
            result.put("message", "该用户名已被使用");
            return result;
        }

        Admin admin = adminService.getById(id);
        if (admin == null) {
            result.put("success", false);
            result.put("message", "管理员不存在");
            return result;
        }
        admin.setAccount(account);
        boolean success = adminService.updateById(admin);
        result.put("success", success);
        if (!success) {
            result.put("message", "更新失败，请重试");
        }
        return result;
    }
    @PostMapping("/category/add")
    public String addCategory(@RequestParam String name, RedirectAttributes redirectAttributes) {
        Category category = new Category();
        category.setName(name);
        category.setPid(0);

        try {
            categoryService.save(category);
            redirectAttributes.addFlashAttribute("message", "分类添加成功");
            return "redirect:/admin/category/list";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "分类添加失败: " + e.getMessage());
            return "redirect:/admin/category/add";
        }
    }
    @GetMapping("/category/list")
    public String list(Model model) {
        model.addAttribute("categories", categoryService.list());
        return "category_list";
    }


    @GetMapping("/category/list/del")
    public String delete(@RequestParam Long id, HttpSession session) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", id);
        long goodsCount = goodsService.count(queryWrapper);

        if (goodsCount > 0) {
            // 如果有商品，设置错误消息并重定向回列表页
            session.setAttribute("errorMsg", "该分类下有商品，不能删除！");
            return "redirect:/admin/category/list";
        }

        // 如果没有商品，执行删除
        boolean deleted = categoryService.removeById(id);
        if (!deleted) {
            session.setAttribute("errorMsg", "删除失败，请稍后重试");
        }

        return "redirect:/admin/category/list";
    }
    @GetMapping("/manager/delete")
    public String deleteManager(@RequestParam Integer id,
                                RedirectAttributes redirectAttributes) {
        try {
            adminService.removeById(id);
            redirectAttributes.addFlashAttribute("message", "管理员删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除失败: " + e.getMessage());
        }
        return "redirect:/admin/user/list";
    }
    @PostMapping("/manager/add")
    public String addManager(@RequestParam String account,
                             @RequestParam String password,
                             RedirectAttributes redirectAttributes) {

        // 检查账号是否已存在
        if (adminService.findByAccount(account) != null) {
            redirectAttributes.addFlashAttribute("error", "账号已存在");
            return "redirect:/admin/user/list";
        }

        // 创建新管理员
        Admin admin = new Admin();
        admin.setAccount(account);
        admin.setPassword(DigestUtils.md5DigestAsHex(password.getBytes())); // 密码加密
        admin.setStatus("1"); // 状态设置为1

        try {
            adminService.save(admin);
            redirectAttributes.addFlashAttribute("message", "管理员添加成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "添加失败: " + e.getMessage());
        }

        return "redirect:/admin/user/list";
    }
    @GetMapping("/user/list")
    public String userList(Model model, HttpSession session, @RequestParam(defaultValue = "1") int page,
                           @RequestParam(required = false) String account,
                           @RequestParam(required = false) String email,
                           @RequestParam(required = false) String telphone) {
        System.out.println("用户列表页面");
//        List<User> UserList = userServiceImpl.getAllUsers();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(account)) {
            queryWrapper.like("account", account);
        }
        if (StringUtils.isNotBlank(email)) {
            queryWrapper.like("email", email);
        }
        if (StringUtils.isNotBlank(telphone)) {
            queryWrapper.like("telphone", telphone);
        }
        IPage<User> byPage = userServiceImpl.findByPage(page, PAGE_SIZE,queryWrapper);
        List<Admin> adminList = adminService.list();
//        System.out.println(UserList);
//        model.addAttribute("userNewList", byPage.getRecords());
        model.addAttribute("currentPage", byPage.getCurrent());
        model.addAttribute("totalPages", byPage.getPages());
        model.addAttribute("total", byPage.getTotal());
        model.addAttribute("userList", byPage.getRecords());
        model.addAttribute("adminList",adminList);
        System.out.println(byPage.getRecords());
        return "admin_list";
    }

    @PostMapping("/goods/add")
    public String addGoods(GoodsDto goodsDto) {
        boolean b = goodsService.insertGood(goodsDto);

        return "redirect:/";
    }

    @PostMapping("/upload/good")
    @ResponseBody
    public String uploadGoodPhotos(MultipartFile file) throws Exception {
        return goodsService.addMediaFilesToMinIO(file);
    }


    @GetMapping("/user/freeze")
    public String freezeUser(@RequestParam Long id) {
        redisService.clearUserCache();
        userServiceImpl.freezeUser(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/user/unfreeze")
    public String unfreezeUser(@RequestParam Long id) {
        redisService.clearUserCache();

        userServiceImpl.unfreezeUser(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/user/blacklist/add")
    public String addToBlacklist(@RequestParam Long id) {
        redisService.clearUserCache();

        userServiceImpl.addToBlacklist(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/user/blacklist/remove")
    public String removeFromBlacklist(@RequestParam Long id) {
        redisService.clearUserCache();

        userServiceImpl.removeFromBlacklist(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/user/delete")
    public String deleteUser(@RequestParam Long id) {
        redisService.clearUserCache();

        userServiceImpl.deleteUser(id);
        return "redirect:/admin/user/list";
    }
}
